package org.yufan.exception;

import org.springframework.core.annotation.AnnotationUtils;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerExceptionResolver;
import org.springframework.web.servlet.ModelAndView;
import org.yufan.result.Result;
import org.yufan.result.ResultUtils;
import org.yufan.utils.JsonUtils;
import org.yufan.utils.ResponseUtils;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.Method;

/**
 * Created by zxd on 2018/3/22.
 */
public class CustomerHandlerException implements HandlerExceptionResolver{


    @Override
    public ModelAndView resolveException(HttpServletRequest request, HttpServletResponse response, Object handler, Exception exception) {
        ModelAndView modelAndView=new ModelAndView();
        String msg;
        if(exception instanceof CustomException){
            //如果是自定义异常
            msg=exception.getMessage();
        }else{
            //如果是不可预期异常
            exception.printStackTrace();;
            msg="对不起，系统开小差了!";
        }

        HandlerMethod handlerMethod= (HandlerMethod) handler;
        //获取controller调用的方法
        Method method = handlerMethod.getMethod();

        //1.判断方法上有没有responseBody注解
        //2.判断方法的返回是不是responseEntity方法
        ResponseBody responseBody = AnnotationUtils.findAnnotation(method,
                ResponseBody.class);
        if(responseBody!=null|| ResponseEntity.class.getName().
                equals(method.getReturnType().getName())){
            //返回json数据
            Result result= ResultUtils.buildFail(500,msg);
            //将结果集转成json对象
            String json=JsonUtils.objectToJson(result);
            //响应给调用者
            ResponseUtils.responseJson(response,json);
            return modelAndView;
        }

        //如果是jsp页面直接跳转到jsp的错误页面
        modelAndView.setViewName("error");
        modelAndView.addObject("msg",msg);
        return modelAndView;
    }
}
